package com.cdh.search.listener;

import cn.hutool.json.JSONUtil;
import com.cdh.search.client.ElasticsearchConfig;
import com.cdh.search.domain.po.ItemDoc;

import com.heima.client.ItemClient;
import com.heima.dto.ItemDTO;
import com.hmall.common.utils.BeanUtils;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {

    private final ElasticsearchConfig ElasticsearchConfig;

    RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http://192.168.100.128:9200")
    ));

    private final ItemClient itemClient;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.update.queue"),
            exchange = @Exchange(name = "item-exchange", delayed = "true"),
            key = "item.update"
    ))
    public void listenItemUpdateMessage(Long orderId) throws IOException {
        ItemDTO itemDTO = itemClient.queryItemById(orderId);
        ItemDoc itemDoc = BeanUtils.copyBean(itemDTO, ItemDoc.class);
        IndexRequest request = new IndexRequest("items")
                .id(itemDoc.getId())
                .source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        ElasticsearchConfig.elasticsearchClient().index(request, RequestOptions.DEFAULT);


    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "item.datele.queue"),
            exchange = @Exchange(name = "item-exchange", delayed = "true"),
            key = "item.delete"
    ))
    public void listenItemDateleMessage(Long orderId) throws IOException {
        String id = String.valueOf(orderId);
        DeleteRequest request = new DeleteRequest("items").id(id);
        ElasticsearchConfig.elasticsearchClient().delete(request, RequestOptions.DEFAULT);
    }
}